package com.yanqu.road.net.operator;

import com.yanqu.road.connect.ServerConnectionGroup;
import com.yanqu.road.connect.YanQuConnection;
import com.yanqu.road.message.YanQuMessage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServerSessionGroupOperator {

    private static Logger logger = LogManager.getLogger(ServerSessionGroupOperator.class.getName());

    private int serverCount = 0;
    private Object lockObj = new Object();
    private Map<Long, ServerConnectionGroup> serverSessionGroupMap = new ConcurrentHashMap<>();


    public void setServerCount(int serverCount) {
        this.serverCount = serverCount;
    }

    public Map<Long, ServerConnectionGroup> getServerSessionGroupMap() {
        return serverSessionGroupMap;
    }


    public void remove(long id) {
        serverSessionGroupMap.remove(id);
    }

    public ServerConnectionGroup getGroupByIndex(long idx) {
        return serverSessionGroupMap.get(idx);
    }

    public ServerConnectionGroup addSessionGroup(long serverIndex, YanQuConnection session, int count, int idx) {
        if (!serverSessionGroupMap.containsKey(serverIndex)) {
            synchronized (lockObj) {
                if (!serverSessionGroupMap.containsKey(serverIndex)) {
                    ServerConnectionGroup group = new ServerConnectionGroup(count);
                    serverSessionGroupMap.put(serverIndex, group);
                }
            }
        }
        ServerConnectionGroup group = serverSessionGroupMap.get(serverIndex);
        group.addConnection(session, idx);
        return group;
    }

    /**
     * 发送数据
     * @param playerId
     * @param packet
     */
    public void sendPacket(YanQuMessage packet, long playerId) {
        if (serverSessionGroupMap.size() == 0 || serverCount == 0) {
            logger.error("no server found");
            return;
        }

        if (playerId <= 0) {
            for (ServerConnectionGroup group : serverSessionGroupMap.values()) {
                group.write(packet.getPlayerId(), packet);
                break;
            }
        } else {
            long idx = (playerId % serverCount);
            ServerConnectionGroup group = getGroupByIndex(idx);
            if (group != null) {
                group.sendPacket(playerId, packet);
            } else {
                logger.error("can't find link {}, playerId:{},code:{}, groupNum:{}.", idx, playerId, packet.getCode(), serverSessionGroupMap.size());
            }
        }
    }
}
